import Api from 'Api/index';
import appConfig from 'AppConfig/index';
import * as common from "Commons/index";
import dayjs from "dayjs";
import globalBehavior from 'Behaviors/global';

Page({
    behaviors: [globalBehavior],
    data: {
        frontNumber: [],
        backzoneNumber: [],
        resultList:[],
        todayDayList:[],
        todayDay:'',
        popShow:"",
        period:"未知",
		historyList:[],
		periodWinData:{},
        defaultData:{},
		periodNumber:null,
		
		lotto_numbers1:"05,12,19,28,31,06,11",
		lotto_numbers2:"04,06,16,28,31,04,06",
    },
    async onLoad (options) {
        wx.setNavigationBarTitle({
            title: '超级大乐透'
        })
        this.initMap()
        /**
         * 最新器
         */
        this.data.periodWinData = await this.getPeriodWinData();
        
        console.log("最近开奖的一期：",this.data.periodWinData)
		// 创建下一期
		this.data.period = this.data.periodWinData.period + 1;
		this.setData({
			period:this.data.period,
			periodWinData:this.data.periodWinData
        })
        
        this.getCaipiaoList();
        
        // 更新开奖数据
        Api.caipiaoWincodePeriod({
            draw_number:Number(this.data.periodWinData.period),
            winning_numbers:this.data.periodWinData.win.join(",")
        });

    },
	updataClick1(){
        Api.caipiaoCreate({
            lotto_numbers:this.data.lotto_numbers1,
            draw_number:Number(this.data.period), // 第几期
        });
	},
	updataClick2(){
        Api.caipiaoCreate({
            lotto_numbers:this.data.lotto_numbers2,
            draw_number:Number(this.data.period), // 第几期
        });
	},
    initMap(){
        let arr = this.getNumberList(35)
        let arr2 = this.getNumberList(12)
        this.setData({
            frontNumber: arr,
            backzoneNumber: arr2
        })

    },
    openPageHistory(){
        wx.navigateTo({
            url: '/package/pages-caipiao/history/history',
        })
    },
    openPageRule(){
        this.setData({
            popShow:'rule'
        })
    },
    closePopClick(){
        this.setData({
            popShow:''
        })
    },
    getNumberList(num) {
        let arr = []
        for (let i = 1; i <= num; i++) {
            arr.push({
                show: false,
                num: i < 10 ? '0' + i : i + ''
            })
        }
        return arr;
    },
    changeData(e){
        let { type,item,index } = e.currentTarget.dataset;
        let { frontNumber,backzoneNumber } = this.data;
        if(type==1){
            if(!frontNumber[index].show){
                if(frontNumber.filter((obj)=>{ return obj.show }).length==5) return;
            }
            frontNumber[index].show = !frontNumber[index].show;
        }
        if(type==2){
            if(!backzoneNumber[index].show){
                if(backzoneNumber.filter((obj)=>{ return obj.show }).length==2) return;
            }
            backzoneNumber[index].show = !backzoneNumber[index].show;
        }
        this.setData({
            frontNumber:frontNumber,
            backzoneNumber:backzoneNumber
        })
        this.updataResultList()
    },
    updataResultList(){
        let { frontNumber,backzoneNumber } = this.data;
        let _a = frontNumber.filter((obj)=>{ return obj.show });
        let _b = backzoneNumber.filter((obj)=>{ return obj.show });
        let resultList = []
        if(_a.length==5&&_b.length==2){
            resultList = [].concat(_a.map(item=>{ return {type:1,num:item.num} })).concat(_b.map(item=>{ return {type:2,num:item.num} }))
        }else{
            resultList = []
        }
        this.setData({
            resultList:resultList
        })
    },
    randomClickNumber() {
        let arr01 = [],arr02 = []
        for(let i=0;i<35;i++){ arr01.push(i) }
        for(let i=0;i<12;i++){ arr02.push(i) }
        function getRandom(s,len) {
            s.sort(function () { return 0.5 - Math.random()});
            return s.slice(0,len);
        }
        let result01 = getRandom(arr01,5);
        let result02 = getRandom(arr02,2);
        let { frontNumber,backzoneNumber } = this.data;
        for(let i=0;i<frontNumber.length;i++){
            frontNumber[i].show = false
        }
        for(let i=0;i<backzoneNumber.length;i++){
            backzoneNumber[i].show = false
        }
        let list01=[],list02=[];
        for(let i=0;i<result01.length;i++){
            frontNumber[result01[i]].show = true;
            list01.push(frontNumber[result01[i]].num)
        }
        for(let i=0;i<result02.length;i++){
            backzoneNumber[result02[i]].show = true;
            list02.push(frontNumber[result02[i]].num)
        }
        list01.sort()
        list02.sort()
        
        this.setData({
            frontNumber:frontNumber,
            backzoneNumber:backzoneNumber,
            resultList:list01.map((num)=>{ return {type:1,num:num} }).concat(list02.map((num)=>{ return {type:2,num:num} }))
        })
    },
    
    async submitClickBtn(){
        // if( this.data.todayDayList.length>=2 ){
        //     wx.showModal({
        //         content:"每日最大购买两注哟！",
        //         showCancel:false
        //     })
        //     return
        // }
        let { frontNumber,backzoneNumber } = this.data;
        await Api.caipiaoCreate({
            lotto_numbers:this.data.resultList.map(item=>item.num).join(","),
            draw_number:Number(this.data.period), // 第几期
        });

		wx.showModal({
			content: '记录成功',
			showCancel:false,
			success:()=>{
				for(let i=0;i<frontNumber.length;i++){
					frontNumber[i].show = false
				}
				for(let i=0;i<backzoneNumber.length;i++){
					backzoneNumber[i].show = false
				}
				this.setData({
					frontNumber:frontNumber,
					backzoneNumber:backzoneNumber,
					resultList:[]
				})
				this.getCaipiaoList()
			}
		})
    },
    // 更新直接月份数据
    updataData(){
        if( !this.data.periodNumber ){
            wx.showToast({
                title: '请选输入要更新的期数！',
                icon:"error"
            })
            return;
        }
		this.data.periodWinData = {
			period:Number(this.data.periodNumber),
			prize:0,
			win:this.data.resultList.map(item=>item.num)
        }
		// 创建下一期
        this.data.period = this.data.periodWinData.period + 1;
		this.getCaipiaoList()
    },
    periodInput(e){
        let { value } = e.detail;
        this.data.periodNumber = Number(value);
    },

    async getCaipiaoList(){
        Api.caipiaoList({ 
			isToday:true
		}).then(res=>{
			console.log("res",res)
            if( res.success ){
                res = res.result||{};
                let todayDayList = (res.list||[]).map(item=>{
                    if( item.winning_numbers ){
                        item.winning_numbers = item.winning_numbers.split(",")
                    }else{
                        item.winning_numbers = [];
                    }
                    item.lotto_numbers = item.lotto_numbers.split(",")
                    return item;
				});
				
                let todayDay = dayjs().format("YYYY-MM-DD");
                this.setData({
                    todayDay:todayDay,
                    todayDayList:todayDayList
                })
            }else{
                wx.showModal({
                    content: res.msg,
                    showCancel:false
                })
            }
        })
    },
    onShow: function () {

	},
	getPeriodWinData(){
		return new Promise((resolve,reject)=>{
			wx.request({
				url: 'https://caipiao.ip138.com/daletou/',
				dataType:"其他",
				responseType:"text",
				enableHttp2:true,
				complete:(res=>{
					let html = res.data.replace(' ','');
					html = html.replace('    ','');
					html = html.replace('                               ','');
					html = html.replace('\n\n','');
					html = html.replace('\n\n','');
					let star = html.indexOf('<span class="period">');
					var period = html.substring(star+21,star+21+7);
					let star2 = html.indexOf('总销售额：<span>');
					var prize = html.substring(Number(star2)+11,Number(star2)+11+11)
					let redball = 'cache.ip138.com/public/image/award/redball-';
					var i1 = html.indexOf(redball);
					var str = html.substr(i1-12,520)
					str = str.replace(/\/\/cache.ip138.com\/public\/image\/award\/redball-/g,'');
					str = str.replace(/\/\/cache.ip138.com\/public\/image\/award\/blueball-/g,'');
					str = str.replace(/\n/g,'');
					var b=/alt="\d*"/g
					var s=str.match(b)
					let win = []
					for(var i= 0;i<s.length;i++){
						let num = s[i].replace("alt=",'');
						num = num.replace(/"/g,'');
						win.push(num);
					}
					// let data = {
					// 	period:2024004,
					// 	prize:Number(prize),
					// 	win:["2", "16", "18", "29", "27", "8", "9"]
                    // }
					let data = {
						period:Number(period),
						prize:Number(prize),
						win:win.map(item=>{
							return Number(item)<10?'0'+item:''+item
						})
                    }
					resolve(data)
				})
			})
		})
	}
})